package com.ta.gulimall.product.controller.redisson;

import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class LockController {
    @Autowired
    RedissonClient redissonClient;

    /**
     * 可重入锁
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/lock")
    public String lock() throws InterruptedException {
        RLock lock = redissonClient.getLock("lock");
        try {
            lock.lock();
            System.out.println("==============线程"+ Thread.currentThread().getId() + "在加锁");
            Thread.sleep(3000);
        }finally {
            lock.unlock();
            System.out.println("==============线程"+ Thread.currentThread().getId() + "在解锁");
        }

        return "lock";
    }

    /**
     * 可重入锁：尝试等待锁
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/tryLock")
    public String tryLock() throws InterruptedException {
        RLock lock = redissonClient.getLock("lock");
        if(lock.tryLock(1, TimeUnit.SECONDS)){
            try {
                System.out.println("==============线程"+ Thread.currentThread().getId() + "在加锁");
                Thread.sleep(3000);
            } catch (Exception e){
                throw new RuntimeException("", e);
            } finally {
                lock.unlock();
                System.out.println("==============线程"+ Thread.currentThread().getId() + "在解锁");
            }
            return "tryLock:ok";
        }else{
            return "tryLock:wait";
        }

    }

}
